package com.platform.eureka.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.shared.Application;
import com.netflix.eureka.EurekaServerContext;
import com.netflix.eureka.EurekaServerContextHolder;
import com.netflix.eureka.registry.PeerAwareInstanceRegistry;
import com.platform.eureka.util.HttpService;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description:
 * @author: Hou Dayu
 * @date: Created in 2021/1/15
 */
@Controller
@RequestMapping("/")
public class IndexAction {

    private Logger log = LoggerFactory.getLogger("eureka logs");

    private EurekaServerContext getServerContext() {
        return EurekaServerContextHolder.getInstance().getServerContext();
    }

    private PeerAwareInstanceRegistry getRegistry() {
        return this.getServerContext().getRegistry();
    }

    /**
     * 获取注册中心服务列表
     * @return
     */
    @RequestMapping(value = "/serverList", method = RequestMethod.GET)
    @ResponseBody
    public String eurekaServers(){
        Map<String,Object> data = new HashMap<>();
        List<Application> apps = this.getRegistry().getSortedApplications();
        if (HttpService.isEmpty(apps)) {
            data.put("flag", "F");
            data.put("msg", "没有找到注册服务信息");
            return JSON.toJSONString(data);
        }
        data.put("flag", "T");
        List<Map<String,Object>> listInfo = new ArrayList();
        for(Application app : apps){
            Map<String,Object> appMap = new HashMap<>();
            appMap.put("serverName",app.getName());
            List<InstanceInfo> list = app.getInstances();
            appMap.put("serverNum",list.size());
            List ups = new ArrayList();
            List downs = new ArrayList();
            List<String> downUrls = HttpService.getDownServers().get(app.getName().toLowerCase());
            for(InstanceInfo info:list){
                Map<String,Object> infoMap = new HashMap<>();
                String homeUrl = info.getHomePageUrl();
                String str = HttpService.sendGetHttp(info.getHomePageUrl()+"info",null);
                infoMap.put("contextPath","");
                if(HttpService.isNotNull(str)){
                    com.alibaba.fastjson.JSONObject json = JSON.parseObject(str);
                    if(null != json.getJSONObject("app") && json.getJSONObject("app").containsKey("context-path")) {
                        infoMap.put("contextPath", json.getJSONObject("app").getString("context-path"));
                        homeUrl = homeUrl.replaceAll(json.getJSONObject("app").getString("context-path"),"");
                    }
                }
                String address = info.getIPAddr();
                homeUrl = homeUrl.replaceAll(info.getHostName(),address);
                String ckey = homeUrl+infoMap.get("contextPath");
                if(info.getStatus().toString().equalsIgnoreCase("UP")){
                    infoMap.put("statusPageUrl",info.getHomePageUrl()+"info");
                    infoMap.put("homePageUrl",homeUrl);
                    ups.add(infoMap);
                    appMap.put("up",ups);
                    if(downUrls!= null && downUrls.contains(ckey)){//从下线列表中删除
                        downUrls.remove(ckey);
                    }
                } else if(downUrls!= null && !downUrls.contains(ckey)){
                    infoMap.put("statusPageUrl",homeUrl);
                    infoMap.put("homePageUrl",homeUrl);
                    downs.add(infoMap);
                    appMap.put("down",downs);
                }
            }
            if(downUrls!= null && !downUrls.isEmpty()){//添加没有恢复下线的服务
                for(int q=0;q<downUrls.size();q++){
                    String durl = downUrls.get(q);
                    Map<String,Object> infoMap = new HashMap<>();
                    infoMap.put("statusPageUrl",durl+"info");
                    infoMap.put("homePageUrl",durl);
                    infoMap.put("contextPath","");
                    downs.add(infoMap);
                    appMap.put("down",downs);
                }
            }
            appMap.put("statusUp",ups.size());
            appMap.put("statusDown",downs.size());
            listInfo.add(appMap);
        }
        data.put("total",listInfo.size());
        data.put("rows",listInfo);
        return JSON.toJSONString(data);
    }

    @ResponseBody
    @RequestMapping(value = "/toLine", method = RequestMethod.POST)
    public String serverManager(HttpServletRequest request, HttpServletResponse response) throws Exception{
        String url = request.getParameter("url");
        String type = request.getParameter("type");
        String serverId = request.getParameter("serverId").toLowerCase();
        String reqMsg = IOUtils.toString(request.getInputStream(),"UTF-8");
        if(HttpService.isNotNull(reqMsg)) {
            JSONObject json = JSON.parseObject(reqMsg);
            url = json.getString("url");
            type = json.getString("type");
            serverId = json.getString("serverId");
        }
        String toUrl ="";
        if("on".equals(type)){
            toUrl = url+ "online";
        } else {
            toUrl = url+ "offline?sign=Constant.OFFLINE_KEY";
        }
        if(HttpService.isNotNull(request.getParameter("tokenId"))) {
            toUrl +="&tokenId="+request.getParameter("tokenId");
        }
        String msg = HttpService.sendGetHttp(toUrl,null);
        Map<String,String> data = new HashMap(2);
        if(HttpService.isNull(msg)) {
            msg = "操作失败";
            data.put("flag","F");
        } else {
            List<String> obj = HttpService.getDownServers().get(serverId);
            if(obj==null){
                obj = new ArrayList();
            }
            if("off".equals(type) && "下线成功".equals(msg)){
                obj.add(url);
                HttpService.setDownServers(serverId,obj);
            } else if("on".equals(type) && "上线成功".equals(msg)){
                obj.remove(url);
                if(obj.isEmpty()){
                    HttpService.getDownServers().remove(serverId);
                } else {
                    HttpService.setDownServers(serverId,obj);
                }
            }
            data.put("flag","T");
        }
        data.put("msg",msg);
        return JSON.toJSONString(data);
    }
}
